package com.boxing;

import com.boxing.bean.ResponseData;
import com.boxing.bean.User;
import com.boxing.utils.JDBCUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * 处理登录请求的servlet
 */
@WebServlet(name = "MyServlet", urlPatterns = "/MyServlet")
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().println("登录时不允许使用get方式");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String contentType = req.getHeader("Content-Type");
        if (contentType.contains("x-www-form-urlencoded")){
            // 需要使用键值对的形式来解析 content
            String user = req.getParameter("user");
            String psd = req.getParameter("psd");
            System.out.println("post的参数列表：user：" +user+"   psd："+psd);
        }else if (contentType.contains("json")){
            // 需要使用json形式来解析 content
            ServletInputStream is = req.getInputStream();
            byte[] buffer = new byte[1024];
            StringBuilder sb = new StringBuilder();
            int len;
            while ((len = is.read(buffer, 0, buffer.length)) > 0){
                sb.append(new String(buffer, 0, len));
            }
            // 解析json  gson  fastJson
            Gson gson = new Gson();
            User user = gson.fromJson(sb.toString(), User.class);
            System.out.println("=====user：" +user.toString());
            // 需要去数据库里验证 用户名和密码是否合法
            // jdbc
            try {
                boolean b = JDBCUtils.queryUser(user);
                System.out.println("查询数据库的结果是：" +b);
                // 把数据库的结果显示到前端页面上
                ResponseData responseData;
                if (b){
                    String token = UUID.randomUUID().toString();
                    responseData = new ResponseData(200, "登录成功", new ResponseData.Data(1, token));
                }else {
                    responseData = new ResponseData(200, "用户名或密码不正确", new ResponseData.Data(0, ""));
                }
                resp.getWriter().println(gson.toJson(responseData));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            // 图片 文件 。。。
        }
    }
}
